package com.example.test2.activity;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.test2.R;
import com.example.test2.adapter.MsgAdapter;
import com.example.test2.databinding.ActivityMsgBinding;
import com.example.test2.db.control.UserDbController;
import com.example.test2.db.entity.User;
import com.example.test2.event.MsgEvent;
import com.example.test2.http.Constants;
import com.example.test2.utils.ToastUtils;
import com.example.test2.utils.Tools;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
//聊天界面
public class MsgActivity extends BaseActivity<ActivityMsgBinding> implements View.OnClickListener{

    private UserDbController dbUserController;
    private User user;
    private MsgAdapter chatAdapter;
    private List<String> list = new ArrayList<>();
    private String msg;
    protected void initData() {
        super.initData();
        dbUserController = UserDbController.getInstance(this);
        getBinding().titleBar.setTitle("淘衣库商家");
        initAdapter();
    }

    private void initAdapter(){
        user = dbUserController.searchByName(Constants.PHONE);
        if (null == user)
            return;
        list = user.getMsgList();

        getBinding().rvData.setLayoutManager(new LinearLayoutManager(this));
        if (chatAdapter == null) {
            chatAdapter = new MsgAdapter(this, list);
            getBinding().rvData.setAdapter(chatAdapter);
        } else {
            chatAdapter.setList(list);
            chatAdapter.notifyDataSetChanged();
        }
    }

    protected void initClick(){
        super.initClick();
        getBinding().titleBar.setLeftIconOnClickListener(v -> {finish();});
        getBinding().btSend.setOnClickListener(this);
    }

    protected int initLayout(){
        return R.layout.activity_msg;
    }

    @Override
    protected ActivityMsgBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityMsgBinding.inflate(layoutInflater);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_send:
                send();
                break;
        }
    }

    private void send(){
        msg = getBinding().etMsg.getText().toString();
        if (TextUtils.isEmpty(msg)) {
            ToastUtils.getInstance().show(this, "请输入内容");
            return;
        }
        List<String> list2 = new ArrayList<>(list);
        list2.add(msg);
        user.setMsgList(list2);
        user.setDate(Tools.customFormat(new Date(), "HH:mm"));
        dbUserController.update(user);
        getBinding().etMsg.getText().clear();
        initAdapter();
        EventBus.getDefault().post(new MsgEvent());
    }

}
